#!/bin/bash

# Dify配置脚本
# 用于快速配置Dify API密钥

set -e

echo "=================================="
echo "  Dify API 配置向导"
echo "=================================="
echo ""

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# 配置文件路径
CONFIG_FILE="src/main/resources/application.yml"

# 检查配置文件是否存在
if [ ! -f "$CONFIG_FILE" ]; then
    echo -e "${RED}错误: 找不到配置文件 $CONFIG_FILE${NC}"
    exit 1
fi

echo "步骤 1: 检查Dify服务状态"
echo "-----------------------------------"

# 检查Dify是否运行
if docker ps | grep -q dify; then
    echo -e "${GREEN}✓ Dify服务正在运行${NC}"
else
    echo -e "${YELLOW}⚠ 警告: 未检测到Dify容器${NC}"
    echo "请确保Dify已启动，或者你使用的是远程Dify实例"
    echo ""
fi

echo ""
echo "步骤 2: 配置Dify API"
echo "-----------------------------------"

# 获取当前配置
CURRENT_BASE_URL=$(grep -A 2 "dify:" "$CONFIG_FILE" | grep "base-url:" | awk '{print $2}')
CURRENT_KEY=$(grep -A 3 "dify:" "$CONFIG_FILE" | grep "key:" | awk '{print $2}')

echo "当前配置："
echo "  Base URL: $CURRENT_BASE_URL"
echo "  API Key: ${CURRENT_KEY:0:10}..."
echo ""

# 询问是否修改Base URL
read -p "是否修改Base URL? (y/n，默认n): " CHANGE_URL
CHANGE_URL=${CHANGE_URL:-n}

if [[ "$CHANGE_URL" == "y" || "$CHANGE_URL" == "Y" ]]; then
    echo ""
    echo "常用Base URL选项："
    echo "  1. http://localhost/v1 (本地Docker部署)"
    echo "  2. https://api.dify.ai/v1 (Dify云服务)"
    echo "  3. 自定义URL"
    echo ""
    read -p "请选择 (1-3): " URL_CHOICE
    
    case $URL_CHOICE in
        1)
            NEW_BASE_URL="http://localhost/v1"
            ;;
        2)
            NEW_BASE_URL="https://api.dify.ai/v1"
            ;;
        3)
            read -p "请输入自定义Base URL: " NEW_BASE_URL
            ;;
        *)
            echo -e "${RED}无效选择，保持原配置${NC}"
            NEW_BASE_URL=$CURRENT_BASE_URL
            ;;
    esac
else
    NEW_BASE_URL=$CURRENT_BASE_URL
fi

echo ""
echo "步骤 3: 配置API密钥"
echo "-----------------------------------"
echo ""
echo "如何获取API密钥："
echo "  1. 访问Dify控制台: http://localhost (或你的Dify地址)"
echo "  2. 进入'应用'页面"
echo "  3. 选择或创建一个'聊天助手'应用"
echo "  4. 点击'API访问'获取API密钥"
echo "  5. 复制API密钥（格式: app-xxxxxx）"
echo ""

read -p "请输入API密钥 (留空保持不变): " NEW_API_KEY

if [ -z "$NEW_API_KEY" ]; then
    NEW_API_KEY=$CURRENT_KEY
    echo -e "${YELLOW}保持原API密钥不变${NC}"
else
    # 验证API密钥格式
    if [[ ! "$NEW_API_KEY" =~ ^app- ]]; then
        echo -e "${YELLOW}⚠ 警告: API密钥通常以'app-'开头，请确认密钥正确${NC}"
        read -p "是否继续? (y/n): " CONTINUE
        if [[ "$CONTINUE" != "y" && "$CONTINUE" != "Y" ]]; then
            echo "配置已取消"
            exit 0
        fi
    fi
fi

echo ""
echo "步骤 4: 确认配置"
echo "-----------------------------------"
echo "新配置："
echo "  Base URL: $NEW_BASE_URL"
echo "  API Key: ${NEW_API_KEY:0:10}..."
echo ""

read -p "确认应用此配置? (y/n): " CONFIRM
if [[ "$CONFIRM" != "y" && "$CONFIRM" != "Y" ]]; then
    echo "配置已取消"
    exit 0
fi

echo ""
echo "步骤 5: 更新配置文件"
echo "-----------------------------------"

# 备份原配置文件
cp "$CONFIG_FILE" "${CONFIG_FILE}.backup"
echo "已备份原配置文件到: ${CONFIG_FILE}.backup"

# 更新配置
sed -i.tmp "s|base-url:.*|base-url: $NEW_BASE_URL|g" "$CONFIG_FILE"
sed -i.tmp "s|key:.*|key: $NEW_API_KEY|g" "$CONFIG_FILE"
rm -f "${CONFIG_FILE}.tmp"

echo -e "${GREEN}✓ 配置文件已更新${NC}"

echo ""
echo "步骤 6: 测试配置"
echo "-----------------------------------"

# 检查后端是否运行
if lsof -Pi :8080 -sTCP:LISTEN -t >/dev/null 2>&1; then
    echo -e "${YELLOW}检测到后端服务正在运行（端口8080）${NC}"
    read -p "是否重启后端服务以应用新配置? (y/n): " RESTART
    
    if [[ "$RESTART" == "y" || "$RESTART" == "Y" ]]; then
        echo "正在停止后端服务..."
        PID=$(lsof -ti:8080)
        if [ ! -z "$PID" ]; then
            kill $PID
            sleep 2
            echo -e "${GREEN}✓ 后端服务已停止${NC}"
        fi
        
        echo "正在启动后端服务..."
        nohup mvn spring-boot:run > backend.log 2>&1 &
        echo -e "${GREEN}✓ 后端服务已启动${NC}"
        echo "查看日志: tail -f backend.log"
    else
        echo -e "${YELLOW}请手动重启后端服务以应用新配置${NC}"
    fi
else
    echo "后端服务未运行"
    read -p "是否启动后端服务? (y/n): " START
    
    if [[ "$START" == "y" || "$START" == "Y" ]]; then
        echo "正在启动后端服务..."
        nohup mvn spring-boot:run > backend.log 2>&1 &
        echo -e "${GREEN}✓ 后端服务已启动${NC}"
        echo "查看日志: tail -f backend.log"
    fi
fi

echo ""
echo "=================================="
echo "  配置完成！"
echo "=================================="
echo ""
echo "下一步："
echo "  1. 等待后端服务启动（约30秒）"
echo "  2. 查看日志确认配置: tail -f backend.log"
echo "  3. 测试API: curl -X POST http://localhost:8080/api/qa/ask \\"
echo "              -H 'Content-Type: application/json' \\"
echo "              -d '{\"question\":\"你好\",\"userId\":1}'"
echo "  4. 访问前端: http://localhost:5173"
echo ""
echo "如需帮助，请查看: cat DIFY_SETUP_GUIDE.md"
echo ""
